package org.execute.tool.扫雷;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;
import springfox.documentation.spring.web.json.Json;

import java.util.Scanner;
import java.util.Random;

public class ConsoleMinesweeper {
    private static final int SIZE = 8;      // 游戏区域大小
    private static final int MINES = 10;    // 地雷数量
    private char[][] display;               // 显示给玩家的视图
    private int[][] mines;                  // 实际地雷分布（-1为雷）
    private boolean gameOver;
    private boolean firstMove = true;
    static Jedis jedis = new Jedis("localhost", 6379);

    public ConsoleMinesweeper() {
        initialize();
    }

    // 初始化游戏
    private void initialize() {
        display = new char[SIZE][SIZE];
        mines = new int[SIZE][SIZE];
        gameOver = false;

        // 初始化显示为未打开状态
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                display[i][j] = 'H';
            }
        }
    }

    // 打印当前游戏状态
    private void printBoard() {
        System.out.println("\n  0 1 2 3 4 5 6 7");
        for (int i = 0; i < SIZE; i++) {
            System.out.print(i + " ");
            for (int j = 0; j < SIZE; j++) {
                System.out.print(display[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("剩余雷数: " + MINES);
        //雷场写入缓存
        jedis.set("Minefield", JSON.toJSONString(display));
    }

    // 生成雷区（确保第一次点击安全）
    private void placeMines(int safeRow, int safeCol) {
        Random rand = new Random();
        int count = 0;

        // 生成地雷（排除第一次点击周围3x3区域）
        while (count < MINES) {
            int r = rand.nextInt(SIZE);
            int c = rand.nextInt(SIZE);

            // 安全区域检查
            if (Math.abs(r - safeRow) <= 1 && Math.abs(c - safeCol) <= 1) continue;

            if (mines[r][c] != -1) {
                mines[r][c] = -1;
                count++;
            }
        }

        // 计算周围雷数
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                if (mines[i][j] != -1) {
                    mines[i][j] = countAdjacentMines(i, j);
                }
            }
        }
    }

    // 处理玩家输入
    private void processInput(int row, int col) {
        if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
            System.out.println("输入超出范围！");
            return;
        }

        if (display[row][col] != '■') {
            System.out.println("该位置已打开！");
            return;
        }

        if (firstMove) {
            placeMines(row, col);
            firstMove = false;
        }

        if (mines[row][col] == -1) {
            gameOver = true;
            revealAll();
            System.out.println("你踩到地雷了！游戏结束！");
            return;
        }

        reveal(row, col);
        checkWin();
    }

    // 递归展开安全区域
    private void reveal(int row, int col) {
        if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) return;
        if (display[row][col] != '■') return;

        int value = mines[row][col];
        if (value == -1) return;

        if (value > 0) {
            display[row][col] = (char)(value + '0');
            return;
        }

        display[row][col] = ' ';
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                if (i == 0 && j == 0) continue;
                reveal(row + i, col + j);
            }
        }
    }

    // 计算周围雷数
    private int countAdjacentMines(int row, int col) {
        int count = 0;
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                int r = row + i;
                int c = col + j;
                if (r >= 0 && r < SIZE && c >= 0 && c < SIZE) {
                    if (mines[r][c] == -1) count++;
                }
            }
        }
        return count;
    }

    // 检查胜利条件
    private void checkWin() {
        int unopened = 0;
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                if (display[i][j] == '■' && mines[i][j] != -1) {
                    unopened++;
                }
            }
        }
        if (unopened == 0) {
            gameOver = true;
            System.out.println("恭喜你，扫雷成功！");
        }
    }

    // 显示所有地雷（游戏结束时）
    private void revealAll() {
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                if (mines[i][j] == -1) {
                    display[i][j] = '×';
                }
            }
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ConsoleMinesweeper game = new ConsoleMinesweeper();




        System.out.println("控制台扫雷游戏");
        System.out.println("输入坐标格式：行 列（例如：3 4）");

        while (!game.gameOver) {
            game.printBoard();
            System.out.print("请输入要打开的坐标：");

            try {
                String s=null;
                while (true) {
                    s = jedis.get("Minefield_row_col");
                    if (s != null) {
                        break;
                    }
                    Thread.sleep(500);
                }
                String[] split = s.split(" ");

//                int row = scanner.nextInt();
//                int col = scanner.nextInt();
                game.processInput(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
            } catch (Exception e) {
                System.out.println("输入格式错误！请重新输入");
                scanner.nextLine(); // 清除错误输入
            }
        }

        game.revealAll();
        game.printBoard();
        scanner.close();
    }





}